package com.online_exam.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.online_exam.domain.Question;
import com.online_exam.domain.TextContent;
import com.online_exam.domain.enums.QuestionTypeEnum;
import com.online_exam.domain.question.QuestionItemObject;
import com.online_exam.domain.question.QuestionObject;
import com.online_exam.domain.utility.JsonUtil;
import com.online_exam.repository.SubjectMapper;
import com.online_exam.service.TextContentService;
import com.online_exam.viewmodel.admin.question.QuestionEditVM;
import com.online_exam.repository.QuestionMapper;
import com.online_exam.repository.TextContentMapper;
import com.online_exam.service.QuestionService;
import com.online_exam.viewmodel.admin.question.QuestionItemVM;
import com.online_exam.viewmodel.admin.question.QuestionPageRequestVM;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private TextContentMapper textContentMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    TextContentService textContentService;


    //题目创建
    @Override
    public int insertQuestion(Question question) {
        return questionMapper.insertQuestion(question);
    }

    //根据视图类，拆分为两个主体类：问题+问题对象 问题存进t_question表 问题对象 存进 t_text_content
    @Transactional
    @Override
    public int insertQuestionByVM(QuestionEditVM questionEditVM,Integer userid){
        //问题
        Question question = new Question();

        QuestionObject questionObject = getQuestionObjection(questionEditVM);
        Date date = new Date();

        TextContent textContent = getTextContent(questionObject);
        textContent.setCreateTime(date);
        //必须先插入才能获得id值
        textContentMapper.insertTextContent(textContent);

        //封装成question
        question.setCreateTime(date);
        question.setCreateUser(userid);
        question.setQuestionType(questionEditVM.getQuestionType());
        //判断是单选还是多选
        if (questionEditVM.getCorrectArray()!=null && questionEditVM.getCorrectArray().size()>0){
            question.setCorrect(JSON.toJSONString(questionEditVM.getCorrectArray()));
        }else {
            question.setCorrect(questionEditVM.getCorrect());
        }
        question.setScore(questionEditVM.getScore());
        question.setSubjectId(questionEditVM.getSubjectId());
        question.setDifficult(questionEditVM.getDifficult());
        question.setGradeLevel(questionEditVM.getGradeLevel());
        question.setSubjectId(questionEditVM.getSubjectId());
        question.setDeleted(false);
        question.setInfoTextContentId(textContent.getId());
        return questionMapper.insertQuestion(question);

    }

    @Override
    public List<Question> select(QuestionPageRequestVM vm) {
        return questionMapper.select(vm);
    }

    @Override
    public QuestionEditVM getQuestionEditRequestVM(Integer id) {
        Question question = questionMapper.getById(id);
        return questionToVM(question);
    }

    @Override
    public QuestionEditVM questionToVM(Question question) {
        QuestionEditVM questionEditVM = modelMapper.map(question, QuestionEditVM.class);
        //题目映射
        TextContent questionInfoTextContent = textContentService.selectById(question.getInfoTextContentId());
        //QuestionObject questionObject = modelMapper.map(JSON.parse(questionInfoTextContent.getContent()), QuestionObject.class);
        QuestionObject questionObject = JSON.parseObject(questionInfoTextContent.getContent(), QuestionObject.class);
        questionEditVM.setTitle(questionObject.getTitleContent());

        //答案
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.fromCode(question.getQuestionType());
        switch (questionTypeEnum) {
            case SingleChoice:
            case TrueFalse:
                questionEditVM.setCorrect(question.getCorrect());
                break;
            case ShortAnswer:
                questionEditVM.setCorrect(questionObject.getCorrect());
                break;
            case MultipleChoice:
                System.out.println(question.getCorrect());
                List list = JSON.parseArray(question.getCorrect());
                System.out.println("多选答案："+list);
                questionEditVM.setCorrectArray(list);
                break;
            case GapFilling:
                List<String> correctContent = questionObject.getQuestionItemObjects().stream().map(d -> d.getContent()).collect(Collectors.toList());
                questionEditVM.setCorrectArray(correctContent);
                break;
            default:
                break;
        }
        questionEditVM.setScore(question.getScore());
        questionEditVM.setAnalyze(questionObject.getAnalyze());


        //题目项映射
        List<QuestionItemVM> editItems = questionObject.getQuestionItemObjects().stream()
                .map(o -> {
                    QuestionItemVM questionEditItemVM = modelMapper.map(o, QuestionItemVM.class);
                    if (o.getScore() != null) {
                        questionEditItemVM.setScore(o.getScore());
                    }
                    return questionEditItemVM;
                }).collect(Collectors.toList());
        questionEditVM.setItems(editItems);
        return questionEditVM;
    }

    @Override
    public int deleteQuestionById(Integer id) {
        return questionMapper.deleteById(id);
    }

    @Override
    public int updateQuestion(Question question) {
        return questionMapper.updateQuestion(question);
    }

    /**
     * 根据前端传进来的视图修改
     * @param editVM
     * @return
     */
    @Override
    @Transactional
    public int updateQuestionByEditVM(QuestionEditVM editVM) {

        Integer level = subjectMapper.findById(editVM.getSubjectId()).getLevel();
        Question question = questionMapper.getById(editVM.getId());
        question.setGradeLevel(level);
        question.setDifficult(editVM.getDifficult());
        question.setScore(editVM.getScore());
        String correct="";
//        String correct=(editVM.getCorrectArray()!=null&&editVM.getCorrectArray().size()>0)?editVM.getCorrectArray().toString():editVM.getCorrect();
        if (editVM.getCorrectArray()!=null&&editVM.getCorrectArray().size()>0){
            correct=JSON.toJSONString(editVM.getCorrectArray());
            question.setCorrect(correct);
        }else{
            correct=editVM.getCorrect();
            question.setCorrect(correct);
        }
        question.setCorrect(correct);
        question.setSubjectId(editVM.getSubjectId());
        editVM.setCorrect(correct);
        //更新textcontent对应数据
        QuestionObject questionObjection = getQuestionObjection(editVM);
        TextContent textContent = textContentMapper.select(question.getInfoTextContentId());
        String jsonStr = JsonUtil.toJsonStr(questionObjection);
        System.out.println("==============="+jsonStr);
        textContent.setContent(jsonStr);
        textContent.setCreateTime(question.getCreateTime());
        textContentMapper.updateTextContent(textContent);
        return questionMapper.updateQuestion(question);
    }

    @Override
    public List<Question> selectByIds(List<Integer> ids) {
        return questionMapper.selectByIds(ids);
    }


    /**
     * 抽取问题对象，准备转成json格式存进textContent
     * @param questionEditVM 前端获取到的视图类
     * @return
     */
    public QuestionObject getQuestionObjection(QuestionEditVM questionEditVM){
        QuestionObject questionObject =new QuestionObject();
        questionObject.setAnalyze(questionEditVM.getAnalyze());
        questionObject.setCorrect(questionEditVM.getCorrect());
        questionObject.setTitleContent(questionEditVM.getTitle());

        List<QuestionItemObject> itemObjects = questionEditVM.getItems().stream().map(i ->
                {
                    QuestionItemObject item = new QuestionItemObject();
                    item.setPrefix(i.getPrefix());
                    item.setContent(i.getContent());
                    item.setScore(i.getScore());
                    return item;
                }
        ).collect(Collectors.toList());
        questionObject.setQuestionItemObjects(itemObjects);
        return questionObject;

    }
    public TextContent getTextContent(QuestionObject questionObject){
        String jsonStr = JsonUtil.toJsonStr(questionObject);
        TextContent textContent = new TextContent();
        textContent.setContent(jsonStr);
        return textContent;
    }


}
